package com.example.braden.answergame.modules.main.presenter;

import android.os.AsyncTask;

import com.example.braden.answergame.R;
import com.example.braden.answergame.base.BaseResult;
import com.example.braden.answergame.common.Constant;
import com.example.braden.answergame.common.LogUtils;
import com.example.braden.answergame.common.utils.CommonUtil;
import com.example.braden.answergame.common.utils.RxUtil;
import com.example.braden.answergame.common.view.LoadingDialog;
import com.example.braden.answergame.component.RetrofitSingleton;
import com.example.braden.answergame.modules.main.MainActivity;
import com.example.braden.answergame.modules.main.domain.MyPropEntity;
import com.example.braden.answergame.modules.main.domain.ReadyEntity;
import com.example.braden.answergame.modules.main.domain.UsePropEntity;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import io.reactivex.Observable;
import io.reactivex.functions.Action;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

/**
 * Created by braden on 2018/3/12.
 */

public class MainPresenter implements MainContact.IPresenter {
    private final MainContact.IView iView;
    private RxAppCompatActivity mContext;

    public MainPresenter(MainContact.IView iView, RxAppCompatActivity context) {
        this.iView = iView;
        this.mContext = context;
    }

    @Override
    public void requestStatGame() {
        fetchStartGame(Constant.ROOMID, Constant.OPENID).doOnSubscribe(disposable -> LogUtils.e("开始游戏--doOnSubscribe"))
                .doOnError(throwable -> {
                    LogUtils.e("开始游戏--doOnError:" + throwable.toString());
                    iView.onStartGame(false, null, throwable.toString());
                }).doOnNext(baseResult -> {
            LogUtils.e("开始游戏--doOnNext:" + baseResult.getCode());
            if (baseResult.getCode() == 0) {
                iView.onStartGame(true, baseResult, null);
            } else {
                iView.onStartGame(false, baseResult, baseResult.getMsg());
            }
        }).subscribe();
    }

    /**
     * 退出房间
     */
    @Override
    public void requestQuitGame() {
        fetchQuitGame(Constant.ROOMID, Constant.OPENID).doOnSubscribe(disposable -> {
//          LoadingDialog.getInstance(mContext).showDialog("退出中...");
            LoadingDialog.getInstance(mContext).setIsCancle(false);
        }).doOnError(throwable -> {
            LogUtils.e("退出失败");
            iView.onQuitGame(false, null, "退出失败");
        }).doOnNext(baseResult -> {
            LogUtils.e("退出成功");
            if (baseResult.getCode() == 0) {
                iView.onQuitGame(true, baseResult, null);
            } else {
                iView.onQuitGame(false, baseResult, baseResult.getMsg());
            }
        }).subscribe();
    }

    /**
     * 使用道具
     *
     * @param qid      题目id
     * @param prop_key 道具key
     */
    @Override
    public void requestUseProp(int qid, String prop_key, int is_use) {
        fetchUseProp(Constant.ROOMID, Constant.OPENID, qid, prop_key, is_use).doOnSubscribe(
                disposable -> {
                    LogUtils.e("使用道具---doOnSubscribe");
//                    LoadingDialog.getInstance(mContext)
//                            .showDialog(mContext.getString(R.string.loading));
                }).doOnError(throwable -> {
            LogUtils.e("使用道具---doOnError：" + throwable.toString());
            iView.onUseProp(false, null, throwable.toString());
        }).doOnNext(usePropEntity -> {
            if (usePropEntity.getCode() == 0) {
                iView.onUseProp(true, usePropEntity, null);
            } else {
                iView.onUseProp(false, null, usePropEntity.getMsg());
            }
            LogUtils.e("使用道具---doOnNext:");
        }).doOnComplete(() -> {
//            LoadingDialog.getInstance(mContext).dismissDialog();
            LogUtils.e("使用道具---doOnComplete:");
        }).subscribe();
    }

    @Override
    public void requestReadyGame() {
        fetchReadyData(Constant.ROOMID, Constant.OPENID).doOnSubscribe(disposable -> {
            //设置loading
            LogUtils.e("ready---loading");
            MainActivity.netIsWrong = -1;
        }).doOnError(throwable -> {
            if (throwable instanceof ConnectException) {//网络问题
                iView.onReadyGame(false, null, "网络断开连接，请检查网络");
            } else if (throwable instanceof SocketTimeoutException) {
                iView.onReadyGame(false, null, "网络请求超时，请检查网络");
            } else {
                iView.onReadyGame(false, null, throwable.toString());
            }
            //加载失败
            LogUtils.e("ready---doOnError:" + throwable.toString());
        }).doOnNext(readyEntity -> {
            //加载成功
            LogUtils.e("ready---doOnNext:" + readyEntity.getCode());
            if (readyEntity.getCode() == 0) {
                iView.onReadyGame(true, readyEntity, null);
            } else {
                iView.onReadyGame(false, null, readyEntity.getMsg());
            }
        }).doOnComplete(() -> {
            //加载完成
            LogUtils.e("ready---complete");
        }).subscribe();
    }

    /**
     * 上传答案
     */
    @Override
    public void requestUploadChoose(int qid, int answer) {
        fetchUploadChoose(Constant.ROOMID, Constant.OPENID, qid, answer).doOnError(throwable -> {
            LogUtils.e("上传答案---doOnError:" + throwable.toString());
        }).doOnNext(upload -> {
            LogUtils.e("上传答案---doOnNext:" + upload.getCode());
        }).doOnComplete(() -> {
            LogUtils.e("上传答案---doOnComplete");
        }).subscribe();
    }

    /**
     * 准备接口
     */
    private Observable<ReadyEntity> fetchReadyData(String rid, String openId) {
        return RetrofitSingleton.getInstance()
                .fetchReady(rid, openId)
                .compose(RxUtil.activityLifecycle(mContext));
    }

    /**
     * 上传选项
     */
    private Observable<BaseResult> fetchUploadChoose(String rid, String openId, int qid,
                                                     int answer) {
        return RetrofitSingleton.getInstance()
                .fetchAnswer(rid, openId, qid, answer)
                .compose(RxUtil.activityLifecycle(mContext));
    }

    private Observable<UsePropEntity> fetchUseProp(String rid, String openId, int qid, String prop_key,
                                                   int is_use) {
        return RetrofitSingleton.getInstance()
                .useProp(rid, openId, qid, prop_key, is_use)
                .compose(RxUtil.activityLifecycle(mContext));
    }

    private Observable<BaseResult> fetchStartGame(String rid, String openId) {
        return RetrofitSingleton.getInstance()
                .startGame(rid, openId)
                .compose(RxUtil.activityLifecycle(mContext));
    }

    private Observable<BaseResult> fetchQuitGame(String rid, String openId) {
        return RetrofitSingleton.getInstance()
                .quitGame(rid, openId)
                .compose(RxUtil.activityLifecycle(mContext));
    }
}
